package org.wat.wcy.isi.mmazur.bp.io.model;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.wat.wcy.isi.mmazur.bp.io.BinaryObject;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.TransitionType;

public class Transition extends BinaryObject {

	private final static int NAME_SIZE = 256;
	private final static int COORDINATES_SIZE = 20;

	private IdDesc id;
	private TransitionType type;
	private TransitionCondition condition;
	private String name;
	private List<Coordinate> coordinates;

	public Transition() {
		id = new IdDesc();
		type = TransitionType.NULL;
		condition = new TransitionCondition();
		coordinates = new ArrayList<Coordinate>();
		name = "";
	}

	public IdDesc getId() {
		return id;
	}

	public void setId(IdDesc id) {
		this.id = id;
	}

	public TransitionType getType() {
		return type;
	}

	public void setType(TransitionType type) {
		this.type = type;
	}

	public TransitionCondition getCondition() {
		return condition;
	}

	public void setCondition(TransitionCondition condition) {
		this.condition = condition;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Coordinate> getCoordinates() {
		return coordinates;
	}

	public void setCoordinates(List<Coordinate> coordinates) {
		this.coordinates = coordinates;
	}

	@Override
	public void write(RandomAccessFile raf) {
		try {
			raf.writeInt(type.ordinal());
			id.write(raf);
			byte b[] = Arrays.copyOf(name.getBytes(), NAME_SIZE);
			raf.write(b);
			condition.write(raf);
			int index = 0;
			if (coordinates != null) {
				for (Coordinate coord : coordinates) {
					coord.write(raf);
					index++;
				}
			}
			Coordinate nullCoord = new Coordinate();
			for (int i = 0; i < COORDINATES_SIZE - index; i++) {
				nullCoord.write(raf);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void read(RandomAccessFile raf) {
		try {
			int index = raf.readInt();
			type = TransitionType.values()[index];
			id.read(raf);
			byte b[] = new byte[NAME_SIZE];
			raf.read(b);
			name = new String(b).trim();
			condition.read(raf);
			for (int i = 0; i < COORDINATES_SIZE; i++) {
				Coordinate c = new Coordinate();
				c.read(raf);
				if (c.isNotNull()) {
					coordinates.add(c);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	public String toString() {
		return String.format("Transition[id=%s] type=%s", id != null ? id
				: "NULL", type != null ? type.toString() : "NULL");
	}

	public static int sizeOf() {
		return IdDesc.sizeOf() + (int) (Integer.SIZE / 8) + NAME_SIZE + COORDINATES_SIZE * Coordinate.sizeOf() + 
				+ TransitionCondition.sizeOf();
	}
}
